package com.team24.hotel.controller;

import com.team24.hotel.domain.User;
import com.team24.hotel.domain.UserAvatar;
import com.team24.hotel.service.UserAvatarService;
import com.team24.hotel.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RequestMapping("/information")
@Controller
public class InformationController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserAvatarService userAvatarService;

    @RequestMapping(value = "/find",method = RequestMethod.GET)
    public  String findUser(Model model, HttpSession session){
        String userId= ((User) session.getAttribute("user")).getUserId();
        User user = userService.findByPrimaryKey(userId);
        model.addAttribute("user",user);
        return "information";
    }

    @RequestMapping(value = "/savePic")
    public String savePicture(MultipartFile file, UserAvatar userAvatar) throws IOException {
        if (file.getSize()>0){
            userAvatar.setFileName(file.getOriginalFilename());
            userAvatar.setFileContentType(file.getContentType());
            userAvatar.setFileLength(new BigDecimal(file.getSize()));
            userAvatar.setContent(file.getBytes());
            userAvatarService.saveOrUpdate(userAvatar);
        }
        return "redirect:/information/find";
    }

    @RequestMapping("/getPic")
    public void getPicture(String userId,HttpServletRequest req,HttpServletResponse resp){
        ServletOutputStream out=null;
        if(StringUtils.isNotBlank(userId)){
            try {
                UserAvatar userAvatar=userAvatarService.findByPrimaryKey(userId);
                byte[] contents = userAvatar.getContent();
                InputStream is =new ByteArrayInputStream(contents);
                resp.setContentType("image/*");
                out=resp.getOutputStream();
                int len=0;
                byte[] buf = new byte[1024];
                while((len=is.read(buf,0,1024))!=-1){
                    out.write(buf,0,len);
                }
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

//    @RequestMapping("/download")
//    public ResponseEntity<Resource> downloadPicture(String userId){
//        UserAvatar userAvatar=userAvatarService.findByPrimaryKey(userId);
//        if(userAvatar!=null && userAvatar.getContent()!=null && userAvatar.getContent().length>0){
//            return ResponseEntity.ok()
//                    .contentType(MediaType.parseMediaType(userAvatar.getFileContentType()))
//                    .contentLength(userAvatar.getFileLength().longValue())
//                    .header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\""+userAvatar.getFileName()+"\"")
//                    .body(new ByteArrayResource(userAvatar.getContent()));
//        }else {
//            return (ResponseEntity<Resource>) ResponseEntity.notFound();
//        }
//    }

    @RequestMapping(value = "/save")
    public String saveUser(User user, String stringUserBirthday, HttpServletRequest request){
        HttpSession session = request.getSession();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date date=null;
        try {
            date=simpleDateFormat.parse(stringUserBirthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setUserBirthday(date);
        userService.saveOrUpdate(user);
        User updateUser=userService.findByPrimaryKey(user.getUserId());
        session.setAttribute("user",updateUser);
        return "redirect:/information/find";
    }

    @RequestMapping(value = "/checkPassword",method = RequestMethod.POST)
    @ResponseBody
    public boolean checkPassword(HttpServletRequest req) {
        String currentPassword = req.getParameter("currentPassword");
        String userId = req.getParameter("userId");
        System.out.println(currentPassword);
        System.out.println(userId);
        User user = userService.findByPrimaryKey(userId);
        if (user.getPassword().equals(currentPassword)) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping("/savePassword")
    public String savePassword(User user,String newPassword){
        user.setPassword(newPassword);
        userService.saveOrUpdate(user);
        return "redirect:/information/find";
    }

}
